package br.com.rpteixeira.dao;

import java.util.List;

import javax.persistence.PersistenceException;

import br.com.rpteixeira.entity.Entity;
import br.com.rpteixeira.entity.filter.EntitySearchFilter;
import br.com.rpteixeira.exceptions.ServiceExcetion;
import br.com.rpteixeira.persistence.DAO;
import br.com.rpteixeira.util.UtilGenerics;

@SuppressWarnings("unchecked")
public abstract class AbstractEntityDAO <ENTITY extends Entity,ENTITYSEARCHFILTER extends EntitySearchFilter> implements EntityDAO<ENTITY,ENTITYSEARCHFILTER>
{
    
    public ENTITY insert(ENTITY entity) throws PersistenceException{   	
    	return getDao().insert(entity);
    }
    public ENTITY update(ENTITY entity) throws PersistenceException{
    		return getDao().update(entity);
    }
    public void delete (ENTITY entity) throws PersistenceException{  	
    		getDao().delete(entity);
    }
    protected abstract Object[] doPrepareQueryFrom(StringBuffer query,ENTITYSEARCHFILTER entitysearchfilter);
  
	public List<ENTITY> find(ENTITYSEARCHFILTER entitySearchFilter) throws PersistenceException{
    	StringBuffer query = new StringBuffer();
    	query.append("select oEntidade from "+getEntityType().getName()+" oEntidade ");
    	doPrepareQuery(query,entitySearchFilter);
    	query.append(" where 1=1 ");
    	Object[]args= doPrepareQueryFrom(query, entitySearchFilter);
    	return (List<ENTITY>) getDao().find(query.toString(), args);
    }
    
	protected Class<ENTITY> getEntityType() {
		return (Class<ENTITY>)UtilGenerics.getFirstDeclaredArgument(getClass());
	}
	protected abstract void doPrepareQuery(StringBuffer query,ENTITYSEARCHFILTER entitySearchFilter);
		
	public List<ENTITY> findAll() throws PersistenceException{
		StringBuffer query =new StringBuffer();
		query.append("select oEntidade from "+getEntityType().getName()+" oEntidade");
    	return (List<ENTITY>) getDao().findAll(query.toString());
    }
	/**
	 * @return the dao
	 */
	public abstract DAO<ENTITY> getDao() ;
	
	public ENTITY findById(ENTITY entity) throws ServiceExcetion{
		return getDao().findById(entity);
	}
}
